package com.example.login.com.czf.controller;

import com.example.login.com.czf.biz.UserBizImpl;
import com.example.login.com.czf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Flamenco
 */
@Controller
public class UserController {
    static User stuser;
    @Autowired
    private UserBizImpl userBiz;

    @PostMapping("login")
    public String login(User user, HttpSession session, HttpServletResponse response) {
        User login = this.userBiz.login(user);
        response.setContentType("text/html;charset=utf-8");
        if (login != null) {
            this.stuser = login;
            session.setMaxInactiveInterval(5 * 60);
            session.setAttribute("userName", login.getUserName());
            session.setAttribute("info", null);
            return "main";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print("<script type=\"text/javascript\" charset=\"utf-8\">\n" +
                "    alert(\"账号或密码错误\")\n" +
                "    location.href =\"http://localhost:8080/logins.html\";\n" +
                "</script>");
        out.flush();
        out.close();
        return "";
    }

    @GetMapping("pwdmodify")
    public String pwdmodify(HttpSession session) {
        session.setAttribute("userName", stuser.getUserName());
        return "pwdmodify";
    }

    @PostMapping("update")
    public String update(String newpassword, HttpSession session) {
        int i = this.userBiz.update(newpassword, stuser.getUserCode());
        stuser.setUserPassword(newpassword);
        return "main";
    }

    @ResponseBody
    @GetMapping("check")
    public String check(@RequestParam("oldpassword") String oldpassword, HttpSession session) {
        if (oldpassword.equals(stuser.getUserPassword())) {
            return "{\"result\":\"true\"}";
        }
        return "{\"result\":\"false\"}";
    }

    @GetMapping("logout")
    public String logout(HttpServletRequest request,HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        HttpSession session = request.getSession();
        for (Cookie cookie:cookies){
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        session.invalidate();
        return "redirect:http://localhost:8080/logins.html";
    }
}
